package com.skydroid.h16

import android.content.Context
import android.content.Intent
import android.net.LocalSocket
import android.net.LocalSocketAddress
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.skydroid.h16.utils.String2ByteArrayUtils
import com.skydroid.h16.R
import com.zhouyou.view.seekbar.SignSeekBar
import java.io.IOException
import java.nio.ByteBuffer

/**
 * 获取摇杆舵量示例
 */
class RockerActivity: AppCompatActivity() {
    protected var PACKAGE_HEADER_BUF = "SKYDROID:".toByteArray()

    private var localSocket: LocalSocket? = null

    private var mReadBuffer = ByteBuffer.allocate(4096)

    private var mReadThread : ReadThread? = null

    private var mSeekBarList = ArrayList<SignSeekBar?>()

    private var mTVList = ArrayList<TextView?>()

    @Volatile
    var isConnect:Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_rocker)
        initView()
        openConnect()
    }

    companion object{
        fun start(context: Context){
            context.startActivity(
                Intent(context,
                    RockerActivity::class.java)
            )
        }
    }

    private fun initView(){
        var items = intArrayOf(
            R.id.item1,
            R.id.item2,
            R.id.item3,
            R.id.item4,
            R.id.item5,
            R.id.item6,
            R.id.item7,
            R.id.item8,
            R.id.item9,
            R.id.item10,
            R.id.item11,
            R.id.item12,
            R.id.item13,
            R.id.item14,
            R.id.item15,
            R.id.item16
        )

        for (i in items){
            var item = findViewById<View>(i)
            var searchBar = item.findViewById<SignSeekBar>(R.id.search_bar)
            var tv = item.findViewById<TextView>(R.id.tv)
            mSeekBarList?.add(searchBar)
            mTVList?.add(tv)
        }

        for (v in mSeekBarList){
            v?.isClickable = false
            v?.isEnabled = false
            v?.isFocusable = false
        }
    }

    /**
     * 打开连接
     */
    private fun openConnect(){
        Thread{
            localSocket = LocalSocket(LocalSocket.SOCKET_DGRAM)
            localSocket?.bind(LocalSocketAddress("uart0app"))

            isConnect = true

            mReadThread = ReadThread()
            mReadThread?.start()
        }.start()
    }

    /**
     * 关闭连接
     */
    private fun closeConnect(){
        isConnect = false
        //关闭读取线程
        mReadThread?.interrupt()
        mReadThread = null

        //关闭连接
        try {
            localSocket?.shutdownInput()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        try {
            localSocket?.shutdownOutput()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        try {
            localSocket?.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        try {
            localSocket?.inputStream?.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        try {
            localSocket?.outputStream?.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        localSocket = null

    }


    fun received(datas: ByteArray?) {
        when(datas?.get(PACKAGE_HEADER_BUF.size)){
            0xB1.toByte()->{
                var length = datas[ PACKAGE_HEADER_BUF.size + 1]
                var startIndex = PACKAGE_HEADER_BUF.size + 2
                runOnUiThread{

                    var sb = StringBuilder()
                    for (index in 0 until length step 2){
                        var h = datas[ startIndex + index]
                        var l = datas[ startIndex + index + 1]
                        sb.append("CH${index +1}：")
                            .append( setSeekBar(index/2 , h , l))
                            .append("  ")

                    }
                }
            }
        }
    }



    private fun setSeekBar(index :Int, h :Byte, l :Byte) :Int{
        //ppm=sbus*5/8+874
        var bytes = byteArrayOf(0,0,h,l)
        var sbus = String2ByteArrayUtils.bytes2int(bytes)
//        var ppm = ((sbus * 5) / 8) + 874
//        LogUtils.test("h:${h}   " + "l:${l}   " + "Sbus:$sbus")
        mSeekBarList?.get(index)?.setProgress(sbus.toFloat())
        mTVList?.get(index)?.text = "CH${index +1}"
//        LogUtils.test("progress:${mSeekBarList?.get(index)?.progress}")
        return sbus
    }
    /**
     * 数据读取线程
     */
    inner class ReadThread:Thread(){
        override fun run() {
            try {
                var size = 0
                while (isConnect && !isInterrupted ){
                    if(localSocket?.inputStream == null){
                        return
                    }
                    if (localSocket?.inputStream?.available() == 0) {
                        continue
                    }
                    size = localSocket!!.inputStream!!.read(mReadBuffer.array())
                    if (size > 0) {
                        var tempArray = ByteArray(size)
                        mReadBuffer[tempArray, 0, size]
                        //需要自行处理 粘包拆包问题
                        received(tempArray)
                        Log.e("ReadThread","receive：${String2ByteArrayUtils.bytes2Hex(tempArray)}")
                    }
                    mReadBuffer.clear()
                }
            }catch (e:InterruptedException){
                e.printStackTrace()
            }catch (e: IOException){
                e.printStackTrace()
            }

        }
    }



    override fun onDestroy() {
        super.onDestroy()
        closeConnect()
    }

}